import { FC } from "react";
import style from "./editCanvas.module.scss";
import { useDispatch } from "react-redux";
import classNames from "classnames";
import useGetComponents from "@/hooks/useGetComponents";
import { ComponentType } from "@/store";
import { getComponentConfByType } from "@/components/QuestionComponents/interface";
import { changeSelected } from "@/store/componentReducer";

function genComponent(component: ComponentType) {
  const { type, props } = component;
  const componentConf = getComponentConfByType(type);
  if (!componentConf) return null;
  const { Component } = componentConf;
  return <Component {...props}></Component>;
}
const EditCanvas: FC = () => {
  const { componentList, selectedId } = useGetComponents();
  const dispatch = useDispatch();

  function handleClick(id: string) {
    dispatch(changeSelected(id));
  }

  return (
    <div className={style.canvas}>
      {componentList.map((item) => {
        const { id } = item;
        // 拼接class name
        const wrapperDefaultClass = style["component_wrapper"];
        const selectedClass = style["selected"];
        const wrapperClass = classNames({
          [wrapperDefaultClass]: true,
          [selectedClass]: selectedId === id,
        });
        return (
          <div key={id} className={wrapperClass} onClick={() => handleClick(id)}>
            <div className={style.component}>{genComponent(item)}</div>
          </div>
        );
      })}
    </div>
  );
};

export default EditCanvas;
